import time
import requests
from datetime import datetime
from Fpq.Guanhui.Gh_yegangcl import ye_gang_chuan_lou

# Django REST framework API地址
API_URL = "http://222.134.245.144:17000/weizhang/VioModel/"


def send_fault_to_api(fault_info):
    """推送故障信息到REST API"""
    try:
        response = requests.post(API_URL, json=fault_info)
        if response.status_code == 201:
            print(f"✅ 故障推送成功：{fault_info['gu_zhang_miao_shu']}")
        else:
            print(f"❌ 推送失败，状态码：{response.status_code}，响应：{response.text}")
    except requests.exceptions.RequestException as e:
        print(f"🚫 网络请求失败：{str(e)}")


def guan_fa_men_nei_lou_huo_kai_guan_bu_dao_wei():
    main_flow_rate, chuan_lou = ye_gang_chuan_lou()
    # 定义阀门顺序（前后流量关联的阀门链）
    valve_chain = [
        "xia_ya_jing", "xia_zu_liu", "shang_ya_jing", "shang_zu_liu",
        "xia_zha_ban", "ke_bian_zha_ban", "jian_qie_zha_ban"
    ]

    # 定义阀门流量结构（前流量为当前值，后流量为下一个阀门的前流量）
    valve_flows = {
        # 阀门链中的前后流量关联
        "xia_ya_jing": {"前流量": main_flow_rate, "后流量": 0},
        "xia_zu_liu": {"前流量": 0, "后流量": 0},
        "shang_ya_jing": {"前流量": 0, "后流量": 0},
        "shang_zu_liu": {"前流量": 0, "后流量": 0},
        "xia_zha_ban": {"前流量": 0, "后流量": 0},
        "ke_bian_zha_ban": {"前流量": 0, "后流量": 0},
        "jian_qie_zha_ban": {"前流量": 0, "后流量": 0},
        "管汇调压阀": {"前流量": 0, "后流量": 0},  # 独立前后流量
        "万能调压阀": {"前流量": 0, "后流量": 0},  # 独立前后流量
        # 仅前流量的阀门
        "旁通阀": {"前流量": 0},
        "wan_neng": {"前流量": 0},
        "上闸板阀": {"前流量": 0}
    }

    # 模拟正常流量传递（无泄漏时，后流量 = 下一个阀门的前流量）
    for i in range(len(valve_chain) - 1):
        current_valve = valve_chain[i]
        next_valve = valve_chain[i + 1]
        valve_flows[current_valve]["后流量"] = valve_flows[next_valve]["前流量"] = main_flow_rate - (i + 1) * 5

    # 单独设置管汇调压阀和万能调压阀的前后流量（模拟独立调节）
    valve_flows["管汇调压阀"]["前流量"] = 30  # 前流量来自其他路径
    valve_flows["管汇调压阀"]["后流量"] = 30  # 后流量独立调节
    valve_flows["万能调压阀"]["前流量"] = 20  # 前流量来自其他路径
    valve_flows["万能调压阀"]["后流量"] = 10  # 后流量独立调节
    # 模拟旁通阀、万能阀、上闸板阀仅前流量（无后流量）
    valve_flows["旁通阀"]["前流量"] = 0
    valve_flows["wan_neng"]["前流量"] = 0
    valve_flows["上闸板阀"]["前流量"] = 0
    valve_flows["jian_qie_zha_ban"]["后流量"] = valve_flows["上闸板阀"]["前流量"]

    # ---------- 内漏检测逻辑 ----------
    # 情况1：单个阀门内漏（当前后流量存在，下一个前流量为0）
    def check_single_leak():
        for i in range(len(valve_chain) - 1):
            current_valve = valve_chain[i]
            next_valve = valve_chain[i + 1]
            if (valve_flows[current_valve]["后流量"] != valve_flows[next_valve]["前流量"] and chuan_lou.get(next_valve,
                                                                                                            False)):
                print(f"{current_valve}内漏或未开启")
                fault_info = {
                    "gu_zhang_ming_cheng": "阀门内漏或未开启",
                    "she_bei_ming_cheng": current_valve,
                    "she_bei_qu_yu": "管汇系统",
                    "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                    "gu_zhang_lei_xing": "阀门故障",
                    "shi_ji_zhi": valve_flows[current_valve]["后流量"],
                    "gao_jing_zhi": valve_flows[next_valve]["前流量"],
                    "gu_zhang_miao_shu": f"{current_valve} 内漏或未开启，当前后流量为 {valve_flows[current_valve]['后流量']}，下一个阀门前流量为 {valve_flows[next_valve]['前流量']}",
                    "chu_li_zhuang_tai": "未处理"
                }
                send_fault_to_api(fault_info)

        # 检查管汇/万能调压阀独立流量是否异常
        for valve in ["管汇调压阀", "万能调压阀"]:
            if (valve_flows[valve]["前流量"] != valve_flows[valve]["后流量"] and chuan_lou.get(valve, False)):
                print(f"{valve}内漏或调节异常")
                fault_info = {
                    "gu_zhang_ming_cheng": "阀门内漏或调节异常",
                    "she_bei_ming_cheng": valve,
                    "she_bei_qu_yu": "管汇系统",
                    "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                    "gu_zhang_lei_xing": "阀门故障",
                    "shi_ji_zhi": valve_flows[valve]["后流量"],
                    "gao_jing_zhi": valve_flows[valve]["前流量"],
                    "gu_zhang_miao_shu": f"{valve} 内漏或调节异常，前流量为 {valve_flows[valve]['前流量']}，后流量为 {valve_flows[valve]['后流量']}",
                    "chu_li_zhuang_tai": "未处理"
                }
                send_fault_to_api(fault_info)

        for valve in ["wan_neng", "上闸板阀", "旁通阀"]:
            if valve_flows[valve]["前流量"] != 0 and chuan_lou.get(valve, False):
                print(f"{valve}内漏或调节异常")
                fault_info = {
                    "gu_zhang_ming_cheng": "阀门内漏或调节异常",
                    "she_bei_ming_cheng": valve,
                    "she_bei_qu_yu": "管汇系统",
                    "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                    "gu_zhang_lei_xing": "阀门故障",
                    "shi_ji_zhi": valve_flows[valve]["前流量"],
                    "gao_jing_zhi": 0,
                    "gu_zhang_miao_shu": f"{valve} 内漏或调节异常，前流量为 {valve_flows[valve]['前流量']}",
                    "chu_li_zhuang_tai": "未处理"
                }
                send_fault_to_api(fault_info)

    check_single_leak()


if __name__ == "__main__":
    guan_fa_men_nei_lou_huo_kai_guan_bu_dao_wei()
